using System;
using System.Collections;
using FyberPlugin;
using UnityEngine;

public class FyberWrapper : MonoBehaviour
{
	private const string STR_COUNT_VIDEO = "countVideoWathes";

	private const string STR_LAST_VIDEO_VIEW_DAY = "LastVideoViewDay";

	private const string APP_ID = "34803";

	private const string SECURITY_TOKEN = "8521c160c1bb5501fe78a8f814876e6f";

	public static FyberWrapper instance;

	[HideInInspector]
	public bool firstCheck = true;

	public bool rewardedVideoAvailable;

	[HideInInspector]
	public ADSLocation leaveLocation;

	[HideInInspector]
	public static bool firstShowDelay = true;

	private bool _interstititalReadyToShow = true;

	private bool _adsAvailable;

	private int _showTotal;

	private IEnumerator _waitSuccessInterstitialRequest;

	private IEnumerator _waitForNewInterstitialShow;

	private int _countVideoWathes;

	private bool checkRewardedVideoInProgress;

	private RVRequestLocation lastRWRequestLocation;

	private int _interstitialCurrentRequestCount;

	private Ad _interstitialAd;

	private Ad _rewardedVideoAd;

	public static event Action<bool> adsInProgress;

	public static event Action successVideoWatch;

	public static event Action canceledVideoWatch;

	public static event Action dailyCoinsUnavailable;

	public static event Action<bool> videoAvailability;

	public static event Action<int, string> nextVideo;

	private void Awake()
	{
		if (instance == null)
		{
			instance = this;
			UnityEngine.Object.DontDestroyOnLoad(base.gameObject);
			SetCookieAcceptPolicy();
			GetComponent<PromoActionManager>().GetAdvertInfo();
			if (BCWStorage.Get<int>("LastVideoViewDay") >= PromoActionManager.CurrentUnixTimeDay(PromoActionManager.CurrentUnixTimeSecond))
			{
				_countVideoWathes = BCWStorage.Get<int>("countVideoWathes");
			}
		}
		else
		{
			UnityEngine.Object.Destroy(base.gameObject);
		}
	}

	private void OnApplicationPause(bool pauseStatus)
	{
		BCWStorage.Set("countVideoWathes", _countVideoWathes, true);
	}

	private void Start()
	{
		Settings settings2 = Fyber.With("34803").WithSecurityToken("8521c160c1bb5501fe78a8f814876e6f").Start();
		FyberCallback.NativeError += OnNativeExceptionReceivedFromSDK;
		FyberCallback.RequestFail += OnRequestFail;
		FyberCallback.AdAvailable += OnAdAvailable;
		FyberCallback.AdNotAvailable += OnAdNotAvailable;
		FyberCallback.AdStarted += OnAdStarted;
		FyberCallback.AdFinished += OnAdFinished;
	}

	private void OnAdAvailable(Ad ad)
	{
		BCWDebug.Log("AdAvailable: " + ad.AdFormat, "Fyber");
		switch (ad.AdFormat)
		{
		case AdFormat.INTERSTITIAL:
			_adsAvailable = true;
			_interstitialAd = ad;
			break;
		case AdFormat.REWARDED_VIDEO:
			rewardedVideoAvailable = true;
			_rewardedVideoAd = ad;
			if (FyberWrapper.videoAvailability != null)
			{
				FyberWrapper.videoAvailability(true);
			}
			checkRewardedVideoInProgress = false;
			break;
		}
	}

	private void OnAdNotAvailable(AdFormat adFormat)
	{
		BCWDebug.LogWarning("AdNotAvailable: " + adFormat, "Fyber");
		switch (adFormat)
		{
		case AdFormat.INTERSTITIAL:
			_adsAvailable = false;
			_interstitialAd = null;
			if (_interstitialCurrentRequestCount < PromoActionManager.fyber.interstitialRequestCount)
			{
				CheckInterstitialWithDelay();
				break;
			}
			BCWDebug.Log("ShowInterstialAfterDelay OnAdNotAvailable", "Fyber");
			ShowInterstialAfterDelay();
			break;
		case AdFormat.REWARDED_VIDEO:
			rewardedVideoAvailable = false;
			_rewardedVideoAd = null;
			if (lastRWRequestLocation == RVRequestLocation.Button && FyberWrapper.videoAvailability != null)
			{
				FyberWrapper.videoAvailability(false);
			}
			checkRewardedVideoInProgress = false;
			break;
		}
	}

	private void OnAdStarted(Ad ad)
	{
	}

	private void OnAdFinished(AdResult result)
	{
		BCWDebug.Log(result.ToString() + " result: " + result.Message, "Fyber");
		if (FyberWrapper.adsInProgress != null)
		{
			FyberWrapper.adsInProgress(false);
		}
		switch (result.AdFormat)
		{
		case AdFormat.INTERSTITIAL:
			BCWDebug.Log("ShowInterstialAfterDelay OnAdFinished", "Fyber");
			_interstitialAd = null;
			ShowInterstialAfterDelay();
			break;
		case AdFormat.REWARDED_VIDEO:
			if (result.Message == "CLOSE_FINISHED")
			{
				if (FyberWrapper.successVideoWatch != null)
				{
					FyberWrapper.successVideoWatch();
				}
				rewardedVideoAvailable = false;
				_rewardedVideoAd = null;
				BCWStorage.Set("LastVideoViewDay", PromoActionManager.CurrentUnixTimeDay(PromoActionManager.CurrentUnixTimeSecond), true);
				_countVideoWathes++;
				CheckRVAvailability();
			}
			else
			{
				rewardedVideoAvailable = false;
				_rewardedVideoAd = null;
				if (FyberWrapper.canceledVideoWatch != null)
				{
					FyberWrapper.canceledVideoWatch();
				}
			}
			break;
		}
	}

	public void OnNativeExceptionReceivedFromSDK(string message)
	{
		if (lastRWRequestLocation == RVRequestLocation.Button && FyberWrapper.videoAvailability != null)
		{
			FyberWrapper.videoAvailability(false);
		}
		if (FyberWrapper.adsInProgress != null)
		{
			FyberWrapper.adsInProgress(false);
		}
		checkRewardedVideoInProgress = false;
		BCWDebug.Log("ShowInterstialAfterDelay OnNativeExceptionReceivedFromSDK", "Fyber");
		ShowInterstialAfterDelay();
		BCWDebug.LogError(message, "Fyber");
	}

	private void OnRequestFail(RequestError error)
	{
		if (lastRWRequestLocation == RVRequestLocation.Button && FyberWrapper.videoAvailability != null)
		{
			FyberWrapper.videoAvailability(false);
		}
		_adsAvailable = false;
		_interstititalReadyToShow = false;
		_interstitialAd = null;
		_rewardedVideoAd = null;
		checkRewardedVideoInProgress = false;
		BCWDebug.Log("ShowInterstialAfterDelay OnRequestFail", "Fyber");
		ShowInterstialAfterDelay();
		BCWDebug.LogError("OnRequestError: " + error.Description, "Fyber");
	}

	public bool ShowAds(ADSLocation location = ADSLocation.None, bool force = false)
	{
		bool flag = false;
		bool flag2;
		switch (location)
		{
		case ADSLocation.PvP:
			flag2 = PromoActionManager.fyber.pvpMaps;
			break;
		case ADSLocation.Lobby:
			flag2 = PromoActionManager.fyber.lobby;
			break;
		case ADSLocation.LoadAdventure:
			flag2 = PromoActionManager.fyber.loadAdventure;
			break;
		case ADSLocation.LoadSandbox:
			flag2 = PromoActionManager.fyber.loadSandbox;
			break;
		case ADSLocation.LeavePvp:
			flag2 = PromoActionManager.fyber.leavePvp;
			flag = true;
			break;
		case ADSLocation.LeaveSandbox:
			flag2 = PromoActionManager.fyber.leaveSandbox;
			flag = true;
			break;
		case ADSLocation.PvpMatchEnd:
			flag2 = PromoActionManager.fyber.pvpMatchEnd;
			break;
		case ADSLocation.LeaveAdventure:
			flag2 = PromoActionManager.fyber.leaveAdventure;
			flag = true;
			break;
		case ADSLocation.LeaveTutorial:
			flag2 = false;
			break;
		case ADSLocation.TransilitionToThePost:
			flag2 = PromoActionManager.fyber.transilitionToThePost;
			break;
		case ADSLocation.None:
			flag2 = false;
			break;
		default:
			flag2 = true;
			break;
		}
		if (flag2 || force)
		{
			if (!_adsAvailable || !_interstititalReadyToShow || !flag2)
			{
			}
			if (_adsAvailable && _interstititalReadyToShow && ((_showTotal <= PromoActionManager.fyber.ShowTimesTotal && flag2) || force))
			{
				if (flag)
				{
					GC.Collect();
					Resources.UnloadUnusedAssets();
				}
				if (_interstitialAd != null)
				{
					if (FyberWrapper.adsInProgress != null)
					{
						FyberWrapper.adsInProgress(true);
					}
					_interstitialAd.Start();
				}
				BCWDebug.Log("ShowInterstialAfterDelay ShowAds", "Fyber");
				ShowInterstialAfterDelay();
				_adsAvailable = false;
				_interstititalReadyToShow = false;
				_showTotal++;
				return true;
			}
		}
		return false;
	}

	public void CheckAds()
	{
		if (!PromoActionManager.fyber.enabled || (!PromoActionManager.fyber.ShowToNew && PromoActionManager.NewUser(PromoActionManager.fyber.newUserStatusHours)) || (!PromoActionManager.fyber.ShowToPaying && PromoActionManager.PayingUser()) || PromoActionManager.fyber.ShowTimesTotal == 0)
		{
			_adsAvailable = false;
		}
		else if (!_adsAvailable)
		{
			InterstitialRequester.Create().Request();
		}
	}

	public void ShowRewardedVideo()
	{
		if (_rewardedVideoAd != null)
		{
			if (FyberWrapper.adsInProgress != null)
			{
				FyberWrapper.adsInProgress(true);
			}
			_rewardedVideoAd.Start();
		}
	}

	public void CheckRewardedVideo(RVRequestLocation location)
	{
		bool flag;
		switch (location)
		{
		case RVRequestLocation.Launch:
			flag = PromoActionManager.fyber.rewardedVideoLaunchRequest;
			break;
		case RVRequestLocation.OpenTab:
			flag = PromoActionManager.fyber.rewardedVideoOpenTabRequest;
			break;
		case RVRequestLocation.Button:
			flag = true;
			break;
		default:
			flag = false;
			break;
		}
		BCWDebug.Log(" checkVideoInProgress: " + checkRewardedVideoInProgress + " CheckRVAvailability: " + CheckRVAvailability(), "Fyber");
		if (flag && !checkRewardedVideoInProgress && !rewardedVideoAvailable && CheckRVAvailability())
		{
			checkRewardedVideoInProgress = true;
			lastRWRequestLocation = location;
			RewardedVideoRequester.Create().NotifyUserOnCompletion(false).AddParameter("param", "I-want-the-blockcitywars-account")
				.Request();
		}
	}

	public bool CheckRVAvailability()
	{
		if (_countVideoWathes < PromoActionManager.fyber.reward.Count)
		{
			if (FyberWrapper.nextVideo != null)
			{
				FyberWrapper.nextVideo(PromoActionManager.fyber.reward[_countVideoWathes], PromoActionManager.fyber.rewardType[_countVideoWathes]);
			}
			return true;
		}
		if (FyberWrapper.dailyCoinsUnavailable != null)
		{
			FyberWrapper.dailyCoinsUnavailable();
		}
		return false;
	}

	private void CheckInterstitialWithDelay()
	{
		if (_waitSuccessInterstitialRequest == null)
		{
			_waitSuccessInterstitialRequest = WaitSuccessInterstitialRequest();
			StartCoroutine(_waitSuccessInterstitialRequest);
		}
	}

	private void ShowInterstialAfterDelay()
	{
		if (_waitForNewInterstitialShow != null)
		{
			StopCoroutine(_waitForNewInterstitialShow);
			_waitForNewInterstitialShow = null;
		}
		_waitForNewInterstitialShow = WaitForNewInterstitialShow();
		StartCoroutine(_waitForNewInterstitialShow);
	}

	private IEnumerator WaitForNewInterstitialShow()
	{
		_interstitialCurrentRequestCount = 0;
		_interstititalReadyToShow = false;
		yield return StartCoroutine(WaitDeltaTime());
		CheckAds();
		yield return new WaitForSeconds(PromoActionManager.fyber.interstitialPreRequestTime);
		_interstititalReadyToShow = true;
		_waitForNewInterstitialShow = null;
	}

	private IEnumerator WaitSuccessInterstitialRequest()
	{
		yield return new WaitForSeconds(PromoActionManager.fyber.interstitialDelayBetweenRequests);
		_waitSuccessInterstitialRequest = null;
		_interstitialCurrentRequestCount++;
		BCWDebug.Log("WaitSuccessInterstitialRequest", "Fyber");
		CheckAds();
	}

	private IEnumerator WaitDeltaTime()
	{
		if (!PromoActionManager.NewUser(PromoActionManager.fyber.newUserStatusHours))
		{
			double totalTimePlayed;
			double.TryParse(BCWStorage.Get<string>(settings.keyTotalTimePlayed), out totalTimePlayed);
			double timePlayed = totalTimePlayed + (double)Time.time;
			double curSeconds = TimeSpan.FromSeconds(timePlayed).TotalSeconds;
			double curTimeWithounNoobTime = curSeconds - (double)HourToSecons(PromoActionManager.fyber.newUserStatusHours);
			double maxTimeWithiutNoobTime = HourToSecons(PromoActionManager.fyber.timeForShowMaxTimeInterstitial) - HourToSecons(PromoActionManager.fyber.newUserStatusHours);
			float value = (float)(curTimeWithounNoobTime / maxTimeWithiutNoobTime);
			float timerWaitForNextShow = Mathf.Clamp((1f - value) * (float)PromoActionManager.fyber.minTimeShowInterstitial, PromoActionManager.fyber.maxTimeShowInterstitial, PromoActionManager.fyber.minTimeShowInterstitial);
			BCWDebug.LogError("Show Interstitial After Delay:  " + timerWaitForNextShow * 60f, "Fyber");
			yield return new WaitForSeconds(timerWaitForNextShow * 60f - (float)PromoActionManager.fyber.interstitialPreRequestTime);
		}
		else
		{
			yield return new WaitForSeconds(PromoActionManager.fyber.showFrequency);
		}
	}

	private float HourToSecons(int hour)
	{
		return (float)hour * 60f * 60f;
	}

	public IEnumerator FirstShowDelay()
	{
		while (!PromoActionManager.jsonReaded)
		{
			yield return new WaitForEndOfFrame();
		}
		CheckRewardedVideo(RVRequestLocation.Launch);
		yield return new WaitForSeconds(PromoActionManager.fyber.timeDelay - PromoActionManager.fyber.interstitialPreRequestTime);
		CheckAds();
		yield return new WaitForSeconds(PromoActionManager.fyber.interstitialPreRequestTime);
		firstShowDelay = false;
	}

	private void SetCookieAcceptPolicy()
	{
	}
}
